import { defineStore } from 'pinia';
import type { UserInfo } from '@/types/interface';
import { getUserInfo } from '@/api/login';

const InitUserInfo: UserInfo = {
    id: 0,
    name: '',
    role: '',
};

export const useUserStore = defineStore('user', {
    state: () => ({
        token: 'main_token',
        userInfo: { ...InitUserInfo },
    }),
    getters: {
        id: (state) => {
            return state.userInfo?.id;
        },
        role: (state) => {
            return state.userInfo?.role;
        },
        name: (state) => {
            return state.userInfo?.name;
        },
    },
    actions: {
        setToken(token: string) {
            this.token = token;
            localStorage.setItem('token', token);
        },
        // 获取用户信息
        async getUser() {
            try {
                const data = await getUserInfo();
                this.userInfo = {
                    id: data.id,
                    name: data.name,
                    role: data.role
                };
                return this.userInfo;
            } catch (error) {
                console.error('获取用户信息失败:', error);
                throw error;
            }
        },
        clearUserInfo() {
            this.userInfo = { ...InitUserInfo };
            this.token = 'main_token';
            localStorage.removeItem('token');
        },
    },
    persist: {
        key: 'user'
    }
});

